package cn.xiaolang.common.utils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {
        super();
    }

    public static void main(final String... args) {

        long x = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();

        System.out.println(x);
        System.out.println(System.currentTimeMillis());
        System.out.println(LocalDateTime.now().atZone(ZoneId.of("GMT+08:00")).toInstant().toEpochMilli());
        System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        System.out.println(LocalDateTime.ofEpochSecond(x/1000L, 0, ZoneOffset.ofHours(8)));

        final LocalDateTime d = LocalDateTime.of(2021, 4, 29, 9, 15);
        final LocalDateTime utc1 = DateTimeUtil.toUtc(d);
        final LocalDateTime d2 = LocalDateTime.of(2021, 4, 29, 10, 15);
        final LocalDateTime utc2 = DateTimeUtil.toUtc(d2);


        long long1 = d.toInstant(ZoneOffset.UTC).toEpochMilli();
        long long2 = d2.toInstant(ZoneOffset.UTC).toEpochMilli();
        System.out.println("UTC1: " + long1);
        System.out.println("UTC2: " + long2);
        System.out.println("diff:" + (long2 - long1));
        System.out.println("diff:" + (utc2.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
                - utc1.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));

    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedTime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedTime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
    }

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
    }

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
    }
}